<!--
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2019-05-27 13:28:09
 * @LastEditors: cxguo
 * @LastEditTime: 2019-10-22 17:40:26
 -->
<template>
  <div v-draggable="dragOptions" :class="'layer-iframe'">
    <div
      :class="{'drag-container':true,'shadow': hasShadow}"
      :style="{'z-index':containerIndex,'width':currentArea[0],'left':currentPosition[0],'top':currentPosition[1]}"
    >
      <div v-show="hasTitle" :class="'drag-title'" :style="{'height':options.iframeTitleHeight+'px','line-height':options.iframeTitleHeight+'px'}" @mousedown="btnTitleClick">
        <span>{{ title }}</span>
        <div class="operBtns">
          <a @click="btnReduce">
            <i class="el-icon-minus" />
          </a>
          <a @click="btnClose">
            <i class="el-icon-close" />
          </a>
          <a @click="btnMaximization">
            <i
              v-if="iframeStatus === 'min' || iframeStatus === 'normal'"
              class="el-icon-copy-document"
            />
            <i v-if="iframeStatus === 'max'" class="el-icon-copy-document" />
          </a>
          <a @click="btnShrink">
            <i :class="iconBtnShrink" />
          </a>
        </div>
      </div>
      <div v-show="contentShow" class="drag-con" :style="`height:${dragConHeight}`">
        <div class="vue-content">
          <i class="el-icon-loading" size="18" />
        </div>
        <span class="layer-iframe-resize" @mousedown="onResizeMouseDown" />
      </div>
    </div>
  </div>
</template>

<script>
import { getMaxIndex, getDocArea, getIframeMinPosition, getMousePos, iframeAreaStr2int } from '../utils/tool'
import { setTimeout } from 'timers'
import Vue from 'vue'

export default {
  name: name,
  props: {
    // --- 创建时候的参数 ---
    title: { type: String, default: '请填写标题' }, // 标题
    area: { type: Array, default: () => { return ['800px', 'auto'] } }, // 面积
    position: { type: Array, default: () => { return [] } }, // 面积
    content: { type: Object, default: () => { return { content: '', props: {}} } }, // 内容
    // --全局参数--
    iframes: { type: Object, default: () => { return {} } }, // 所有的iframe
    minPositions: {
      type: Object,
      default: () => { return {} }
    }, // iframe -> 最小状态的座位
    options: { type: Object, default: () => { return { iframeTitleHeight: 40 } } },
    // -- 当前iframe ---
    name: { type: String, default: 'iframe' } // iframe name
  },
  data() {
    return {
      contentShow: true, // 是否显示内容
      iconBtnShrink: 'el-icon-arrow-down', // icon class
      // visible: true, // 是否显示
      mousePosOld: null,
      containerIndex: 1000,
      currentArea: this.area, // 窗口当前大小
      currentPosition: [],
      originalArea: this.area, // 原始窗口大小
      originalPosition: [],
      iframeStatus: 'normal', // 窗口状态: min,max,normal,destory(最小,最大,正常)
      iframeContent: null, // iframeContent 的内容, 用于返回
      iframeMinPosotion: null // iframe 最小状态的座位名字
    }
  },
  computed: {
    hasTitle: function() {
      return this.title !== ''
    },
    hasShadow: function() {
      return this.title !== ''
    },
    dragOptions: function() {
      return {
        trigger: '.drag-title', // 设置能触发拖动的元素的CSS选择器
        body: '.drag-container' // 设置需要移动的元素的CSS选择器
      }
    },
    dragConHeight: function() {
      const str = this.currentArea[1]
      if (str === 'auto') { return str }
      return (str.substring(0, str.length - 2) - this.options.iframeTitleHeight - 2) + 'px'
    }
  },
  watch: {
    iframeStatus: function(val) {
      if (val === 'normal') {
        this.currentPosition = this.originalPosition
        this.currentArea = this.originalArea
      } else if (val === 'min') {
        return
      } else if (val === 'max') {
        this.$el.children[0].style.transform = `translate(0px, 0px)`
        this.currentPosition = [0, 0]
        this.currentArea = [getDocArea().width + 'px', getDocArea().height + 'px']
      }
    }
  },
  created() {
  },
  mounted() {
    this.containerIndex = getMaxIndex()
    this.$nextTick(() => {
      this.initData()
    })
  },
  destroyed() {
    this.iframeStatus = 'destory'
    if (this.iframeMinPosotion) this.iframeMinPosotion.status = 0 // 离开座位
    this.$el.parentNode.removeChild(this.$el)
    this.$emit('on-destroyed', this)
  },
  methods: {
    btnTitleClick() {
      this.containerIndex = getMaxIndex()
      this.$emit('on-click-title', this)
    },
    btnClose() {
      this.$emit('on-close', this)
      this.close()
    },
    btnReduce() {
      this.min()
      this.$emit('on-min', this)
    },
    btnMaximization() {
      this.max()
      this.$emit('on-max', this)
    },
    btnShrink() {
      if (this.contentShow) {
        this.contentShow = false
        this.iconBtnShrink = 'el-icon-arrow-down'
      } else {
        this.contentShow = true
        this.iconBtnShrink = 'el-icon-arrow-up'
      }
    },
    // --- init ---
    /**
     * 初始化数据:
     * 初始化位置/面积
     */
    initData() {
      const that = this
      that.initPosition()
      that.initArea()
      setTimeout(() => {
        that.manualMount()
      }, 100)
    },
    initArea() {},
    initPosition() {
      if (this.position.length !== 0) {
        this.currentPosition = this.position
        this.originalPosition = this.currentPosition
        return
      }
      const iframeArea = iframeAreaStr2int(this)
      const bodyArea = getDocArea()
      this.currentPosition = [
        (bodyArea.width - iframeArea[0]) / 2 + 'px',
        '80px'
      ]
      this.originalPosition = this.currentPosition
    },
    // -- on --
    onResizeMouseDown() {
      const that = this
      that.mousePosOld = getMousePos()
      that.onMouseUp(that)
      that.onMouseMove(that)
    },
    onMouseUp(that) {
      document.body.onmouseup = function() {
        that.mousePosOld = null
      }
    },
    onMouseMove(that) {
      document.body.onmousemove = function() {
        if (that.mousePosOld !== null) {
          var mousePos = getMousePos()
          var mouseDisPos = [
            mousePos[0] - that.mousePosOld[0],
            mousePos[1] - that.mousePosOld[1]
          ]
          var intArea = iframeAreaStr2int(that)
          var targetArea = [
            intArea[0] + mouseDisPos[0] + 'px',
            intArea[1] + mouseDisPos[1] + 'px'
          ]
          that.currentArea = targetArea
          that.mousePosOld = getMousePos()
        }
      }
    },
    /**
     * 手动挂载vue
     */
    manualMount() {
      const vmObjProps = Object.assign(this.content.props, { iframe: this }) || {}
      const vmObj = this.content.content
      this.$nextTick(() => {
        const Profile = Vue.extend(vmObj)
        let Instance = new Profile()
        Instance = Object.assign(Instance, vmObjProps)
        Instance.$mount('.layer-iframe' + ' .vue-content')
        const iframeContent = Instance
        this.$on('hook:beforeDestroy', () => {
          iframeContent.$destroy()
        })
        iframeContent.$parent = this
        this.iframeContent = iframeContent
        iframeContent.$nextTick(() => {
          this.$emit('on-iframecontent-nexttick', iframeContent)
        })
      })
    },
    // api
    // 关闭
    close() {
      this.$destroy(this.name)
    },
    // 最大化
    max() {
      if (this.iframeStatus !== 'normal') {
        this.iframeStatus = 'normal'
      } else if (this.iframeStatus === 'normal') {
        this.iframeStatus = 'max'
      }
    },
    // 最小化
    min() {
      // 1 得到一个座位
      if (this.iframeMinPosotion === null) {
        this.iframeMinPosotion = getIframeMinPosition(this, this.iframes, this.minPositions)
      }
      // 3 入座
      this.$el.children[0].style.transform = `translate(0px, 0px)`
      this.currentPosition = this.iframeMinPosotion.position
      this.iframeStatus = 'min'
      // 4 设置座位状态(有人了)
      this.iframeMinPosotion.status = 1
      // 5 iframe大小
      this.currentArea = ['200px', this.iframeTitleHeight + 'px']
    }
  }
}
</script>

<style>
  .drag-container{position: absolute;
    border: 1px solid #e8eaec;
    border-radius: 2px;}
  .drag-title{
    padding: 0 80px 0 20px;
    font-size: 14px;
    color: #4e5052;
    overflow: hidden;
    background: #fff;
    border-bottom: #e8eaec solid 1px;
  }
  .drag-con{background: #fff; overflow-y:auto}
  .operBtns{ position: absolute; right: 10px; top:0;}
  .layer-iframe-resize{
    position: absolute;
    width: 15px;
    height: 15px;
    right: 0;
    bottom: 0;
    cursor: se-resize;}
  .shadow{
    box-shadow: 1px 1px 10px rgba(0,0,0,.2);
  }
  .demo-spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
  }
  @keyframes ani-demo-spin {
        from { transform: rotate(0deg);}
        50%  { transform: rotate(180deg);}
        to   { transform: rotate(360deg);}
  }

</style>
